<?php

namespace App\Recharge\Api;

use App\Models\H5CombinedOrders;
use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class Jiangsutongka extends AbstractApi
{
    /**
     * @return string
     */
    public function signStr($data,$key = ''): string
    {
        $string = '';
        ksort($data);
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $string .= $this-> signStr($v);
                continue;
            }
            if (($v || $v === 0 || $v === '0') && $k !== 'sign') {
                $string .= "$k=$v&";
            }
        }
        if (empty($key)) {
            return $string;
        }
        $signStr = $string . 'key=' . $key;
        return strtoupper(md5($signStr));
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'out_order_sn'=>$bean->getOrderNo(), //订单号
            'coupon_id'=>$bean->getGoodsId(),//商品编码
            'out_user_sn'=>$bean->getAccount(),//用户账号
            'num'=>$bean->getRechargeNum(),
            'nonce_str'=>md5($bean->getOrderNo()),
            'timestamp'=>time(),
            'notify_url'=>$bean->getNotifyUrl()
        ];
        $array['sign'] = $this->signStr($array,$bean->getSecretKey());
        return $array;
    }
    /**
     * @param PendingRequest $http
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return PromiseInterface
     */
    public function recharge(PendingRequest $http, InterfaceConfiguration $config, BasicInformation $bean): PromiseInterface
    {
        $token = $this->gettoken($bean->getSecretKey(),$bean->getSupplierNum());
        return $this->httpClient($http)->asJson()->withHeader('Authorization', 'bearer '.$token['data']['token'])->post($config->recharge_url, $this->rechargeData($bean));
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $order_sn = $request->input('out_order_sn', '');
        $order_sn_kj = $request->input('order_sn', '');
        $goods_belong = H5CombinedOrders::query()->where('trade_no',$order_sn)->value('supplier_status');
        Log::info($goods_belong);
        $user_data = InterfaceConfiguration::query() -> firstWhere('id',$goods_belong)->toArray();
        $card = $this->getcard($order_sn_kj,$user_data);

        return $this
            ->apiNotifyData($order_sn, $card['status'])
            ->setExecute(true)
            ->setRechargeSuccess($card['status'] == 1)
            ->setCami($card['card']);
    }

    /**
     * @param $key
     * @param $appid
     * @return array|mixed
     */
    public function gettoken($key,$appid){
        $array = [
            'app_id'=>$appid,
            'app_secret'=>$key
        ];
        $curl =  httpClient()->asJson()->post('https://kaqapi.jsrxjt.com/Api/Common/Auth/getToken', $array);
        return $curl->json();
    }

    /**
     * @param $order_sn_kj
     * @param $user_data
     * @return array
     */
    public function getcard($order_sn_kj,$user_data){
        $array = [
            'order_sn'=>$order_sn_kj,
            'timestamp'=>time(),
            'nonce_str'=>md5(uniqid()),
        ];
        $status = 1;
        $array['sign'] = $this->signStr($array,$user_data['iv']);
        $token = $this->gettoken($user_data['iv'],$user_data['appid_title']);
        $res =  httpClient()->asJson()->withHeader('Authorization','bearer '.$token['data']['token'])->post('https://kaqapi.jsrxjt.com/Api/Order/Order/getCard', $array);
        Log::info($res->json());
        $card = $res->json();
        if ($card['msg'] != 'SUCCESS'){
            return [
                'status'=>2,
                'card'=>''
            ];
        }
        $cami_arr = ['sku_one'=>$card['data'][0]['code'], 'sku_two'=>$card['data'][0]['pass'], 'sku_three'=>$card['data'][0]['valid_time'] ?? 'null',];
        return [
            'status'=>$status,
            'card'=>json_encode($cami_arr)
        ];
    }
    /**
     * @return mixed
     */
    public function apiNotifySuccess(): mixed
    {
        return response('{"code":"SUCCESS","msg":"ok"}');
    }
}
